<template>
  <div class="cookbookMain" :style="{height:conHeight+'px' }">
    <div class="line_1">
      <div class="db_inline" style="margin-right: 50px;">
        <span>选择年份</span>
        <Select v-model="time[0]" style="width:200px" @on-change="changeYear">
          <Option v-for="item in yearList" :value="item" :key="item">{{ item }}年</Option>
        </Select>
      </div>
      <div class="db_inline">
        <span>选择月份</span>
        <Select v-model="time[1]" style="width:200px" @on-change="changeMonth">
          <Option v-for="item in 12" :value="item" :key="item">{{ item }}月</Option>
        </Select>
      </div>
    </div>
    <div class="line_2">
      <div style="margin-bottom: 10px;">
        选择周
      </div>
      <RadioGroup v-model="week" @on-change="queryFn">
        <Radio label="apple" v-for="item in weekList" :key="item.ord" :label="item.ord"
               style="margin-right:20px;font-size: 16px;">
          第{{item.ord}}周 ({{item.start}} - {{item.end}})
        </Radio>
      </RadioGroup>
    </div>
    <div class="line_3">
      <Card>
        <p slot="title">当周食谱</p>
        <div slot="extra" v-show="imgList.length!==0">
          <Button type="error" @click="deleteCookbook">
            <Icon type="trash-a" size="15"></Icon>
            删除
          </Button>
        </div>
        <div v-if="imgList.length!==0" style="text-align: center">
          <img class="cookimg" :src="imgList[0].url"
               alt="">
        </div>
        <div v-else>
          <Upload
            type="drag"
            :action="action"
            accept="image/*,.xlx,.xlsx,.doc,.docx"
            :headers="headers"
            :data="uploadData"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
          >
            <div style="padding: 60px 0">
              <Icon type="ios-cloud-upload" size="80" style="color: #3399ff"></Icon>
              <p>上传本周食谱</p>
            </div>
          </Upload>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
  import API from "@/api/api";
  import Axios from 'axios'
  import Cookies from 'js-cookie';

  const fix2 = function (val) {
    if (val < 10) return '0' + val
    else return val
  }
  const getMonthData = function (a, b) {
    //当月1号是周几
    let w = new Date(a, parseInt(b) - 1, 1).getDay();
    if (w == 0) w = 7;
    //第一个周一是几号
    let fw;
    if (w != 1) fw = 7 - w + 2;
    else fw = 1;

    // 当月总天数
    let td = new Date(a, parseInt(b), 0).getDate();

    //当月总共有几周
    let tw = Math.ceil((td - fw + 1) / 7);

    let dateList = []; //日期列表
    let weekList = []; //周列表

    for (let i = fw; i <= td; i++) {
      dateList.push(i)
    }

    for (let i = 0, len = dateList.length; i < len; i += 7) {
      weekList.push(dateList.slice(i, i + 7));
    }

    for (let i = 0; i < weekList.length; i++) {
      let fill = 7 - weekList[i].length;
      for (let m = 1; m <= fill; m++) {
        weekList[i].push(m)
      }
    }

    let config = {
      year: a, //年
      month: b, //月
      first_date_week: w, //当月1号是周几
      first_week_date: fw, //当月第一个周一是几号
      total_days: td, //当月总天数
      weekList: weekList, //周列表
    }

    return config
  }
  export default {
    name: "Cookbook",
    components: {},
    data() {
      let time = new Date();
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let date = time.getDate();
      return {
        conHeight: 0,
        action: Axios.defaults.baseURL + '/cookbook/file',
        headers: {
          Authorization: "Bearer " + Cookies.getJSON('TOKEN'),
        },
        uploadData: {},
        imgList: [],
        week: 1,
        yearList: [], //年份
        monthWeek: {}, //整年份周列表
        weekList: [], //周列表
        time: [year, month, date], //时间
      }
    },
    methods: {
      setHeight() {
        let mHeight = $('.container').outerHeight();
        let hHeight = $('.ivu-card-head').outerHeight();
        let fHeight = $('#footer').outerHeight();
        let cHeight = mHeight - hHeight - fHeight;
        this.conHeight = cHeight-20;
      },
      beforeUpload() {
        this.$Spin.show();
      },
      uploadSuccess(resp, file) {
        if (resp.code !== 200) {
          this.$Notice.error({title: '警告', desc: '上传失败'});
          return;
        }
        this.imgList = [{url: resp.data.url}];
        this.createCookbook(resp.data.key);
      },
      createCookbook(filename) {
        let data = {
          imageList: [{fileName: filename}],
          year: this.time[0],
          month: this.time[1],
          ofweek: this.week
        }
        API.createCookbook(data).then(resp => {
          this.$Spin.hide();
        })
      },
      deleteCookbook() {
        API.deleteCookbook({
          year: this.time[0],
          month: this.time[1],
          ofweek: this.week
        }).then(resp => {
          this.queryFn();
        })
      },
      changeYear(val) {
        this.initMonthWeek();
        this.$nextTick(function () {
          this.changeMonth(this.time[1])
        })
      },
      changeMonth(val) {
        this.weekList = [];
        this.week = 1;
        let list = this.monthWeek[val].weekList;
        let next = val + 1;
        if (next == 13) next = 1;
        for (let i = 0; i < list.length; i++) {
          let start = list[i][0];
          let end = list[i][6];
          let data = {
            ord: i + 1,
            start: val + '月' + start + '日',
            end: '',
          }
          if (end < start) {
            data.end = next + '月' + end + '日'
          } else {
            data.end = val + '月' + end + '日'
          }
          this.weekList.push(data);
        }
        this.queryFn();
      },
      initMonthWeek() {
        for (let i = 1; i < 13; i++) {
          let everyMonth = getMonthData(this.time[0], i);
          this.monthWeek[everyMonth.month] = everyMonth;
        }
      },
      initYearList() {
        let start = this.time[0] - 5;
        let end = this.time[0] + 20;
        for (let i = start; i < end; i++) {
          this.yearList.push(i);
        }
      },
      queryFn() {
        API.fetchCookbook({year: this.time[0], month: this.time[1], week: this.week}).then(resp => {
          this.imgList = resp.data.imageList;
        })
      },
    },
    created() {
      this.initYearList();
      this.changeYear(this.time[0]);
    },
    mounted() {
      this.setHeight();
      this.queryFn();
    }
  }
</script>

<style scoped>
  .cookbookMain {
    width: 100%;
    height: 100%;
    background: #FFFFFF;
    overflow: hidden;
    padding: 20px;
    box-sizing: border-box;
  }

  .line_1,
  .line_2,
  .line_3 {
    margin-bottom: 20px;
    background: #FFFFFF;
    font-size: 16px;
  }

  .cookimg {
    max-width: 90%;
    max-height: 500px;
  }
</style>
